//
//  FANAddPictureView.m
//  Weibo - OC
//
//  Created by user on 16/4/27.
//  Copyright © 2016年 user. All rights reserved.
//

#import "FANAddPictureView.h"
#import "FANAddPictureCell.h"

@interface FANAddPictureView ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;


@end

@implementation FANAddPictureView

- (NSMutableArray *)imageArray{
    
    if (!_imageArray) {
        
        _imageArray = [NSMutableArray array];
    }
    
    return _imageArray;
}

- (UICollectionViewFlowLayout *)flowLayout{
    
    if (!_flowLayout) {
        
        _flowLayout =(UICollectionViewFlowLayout *)self.collectionViewLayout;
    }
    
    return _flowLayout;
}

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {
        
        [self setupUI];
    }
    
    return self;
}

- (void)setupUI{
    
    self.backgroundColor = [UIColor orangeColor];
    
    self.dataSource = self;
    
    self.delegate = self;
    
    [self registerClass:[FANAddPictureCell class] forCellWithReuseIdentifier:@"addCell"];
    
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    CGFloat margin = 5;
    
    CGFloat pictureWH = (self.frame.size.width - 2 * margin)/3;
    
    self.flowLayout.itemSize = CGSizeMake(pictureWH, pictureWH);
    
    self.flowLayout.minimumInteritemSpacing = margin;
    
    self.flowLayout.minimumLineSpacing = margin;
}

- (void)addImageMethod:(UIImage *)image{
    
    [self.imageArray addObject:image];
    
    [self reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.imageArray.count == 0) {
        
        self.hidden = true;
        
    }else{
        
        self.hidden = false;
    }
    
    return self.imageArray.count + (self.imageArray.count == 0 || self.imageArray.count == 9 ? 0 : 1);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    FANAddPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addCell" forIndexPath:indexPath];
    
    if (indexPath.item == self.imageArray.count) {
        
        cell.image = nil;
        
    }else{
        
        cell.image = self.imageArray[indexPath.item];
    }
    
    cell.delectedBlock = ^{
    
        [self.imageArray removeObjectAtIndex:indexPath.item];
        
        [self reloadData];
    };
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.item == self.imageArray.count) {
        
        self.addBlock();
    }
}



@end
